package 数组.二分查找;

import java.sql.Time;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Vote {
    //用一个阻塞队列来缓存数据
    private static BlockingDeque<Integer> voteQueue = new LinkedBlockingDeque<>();

    private static AtomicInteger totalVotes = new AtomicInteger(0);
    private static final Integer maxVotes = 10000;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        Thread consumer = new Thread(new Consumer());
        consumer.start();

        for (int i = 0; i < 10; i++) {
            executorService.submit(new Producer(i));
        }
        executorService.shutdown();


        executorService.awaitTermination(5, TimeUnit.SECONDS);
        consumer.join();
        System.out.println("投标结束" + totalVotes);
    }

    static class Producer implements Runnable {
        int userId;
        public Producer(int userId) {
            this.userId = userId;
        }

        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                try {
                    voteQueue.put(userId);
                    System.out.println("用户" + userId + "投票" + (i + 1) + "次");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    static class Consumer implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    synchronized (voteQueue) {
                        while (voteQueue.size() > 0) {
                            voteQueue.take();
                            totalVotes.incrementAndGet();
                        }
                        System.out.println("当前总投票数" + totalVotes);
                    }
                    if (totalVotes.get() >= maxVotes) {
                        break;
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }
}
